Uec3.AddReturnedItemWindow = Ext.extend(Ext.UecWindow,{

	editCount : 0,
	
	constructor : function(config){
	
		this.partSourceCombo = Uec3.App.dictionary.getCombo("part_source",{hiddenName:'source',allowBlank : true,fieldLabel:'来源',width:90});
		
		this.params = config.params||{};
		
		this.northPanel = new Ext.FormPanel({
			 frame :true,
			 border:false,
			 region : 'north',
			 height:50,
			 items:[{
					layout:'hbox',
					layoutConfig:
                 	 {      
					   align:'middle' 
                    },
                    style:'padding:0px;fontSize:13px;',														
					items:[
					    {xtype:'label',text:'单据号:',style:{width:'50px'}},
					    {xtype:'textfield',name:'codeOfBuyer',style:{width:'100px'}},
					    {xtype:'label',text:'零件编码:',style:{marginLeft:'5px',width:'67px'}},
					    {xtype:'textfield',name:'code',style:{width:'100px'}},
					    {xtype:'label',text:'零件名称:',style:{marginLeft:'5px',width:'67px'}},
					    {xtype:'textfield',name:'name',style:{width:'90px'}},
					    {xtype:'label',text:'来源:',style:{marginLeft:'5px',width:'42px'}},
					    this.partSourceCombo,
					    {xtype:'label',text:'品牌:',style:{marginLeft:'5px',width:'42px'}},
					    {xtype:'textfield',name:'brand',style:{width:'90px'}},
					    {xtype:'label',text:'产地:',style:{marginLeft:'5px',width:'42px'}},
					    {xtype:'textfield',name:'origin',style:{width:'90px'}},
					    {xtype:'button',text:'查找',style:{marginLeft:'15px',width:'75px'},
					     handler:this.searchReceiveByCondition.createDelegate(this)
					   }]
			     }
			 ]
		});
		
		var search_form_store = new Ext.data.JsonStore({
                 root:'root',
                 pruneModifiedRecords:true,
                 fields:[
                    {name:'codeOfBuyer'},                        
                    {name:'code'},
                    {name:'name'},
                    {name:'source'},
                    {name:'measurementUnit'},
                    {name:'carModel'},
                    {name:'orderQuantity',mapping:'quantity'},  // --到货数量
                    {name:'onHand'},  // --剩余数量
                    {name:'cost'},
                    {name:'retailPrice'},
	                {name:'minPrice'},
	                {name:'insurancePrice'},
                    {name:'brand'},
	                {name:'origin'},
	                {name:'storeId'},
	                {name:'storePyCode'},
	                {name:'storeName'},
	                {name:'shelf'},
	                {name:'quantity',mapping:''},  // --退货数量
	                {name:'partId'},
                    {name:'sourceInventoryId'},// 来源零件库存ID(指定了从哪个库存上退货)
	                {name:'nameEn'},
	                {name:'pyCode'},
	                {name:'partCategoryId'},
	                {name:'level1Name'},
	                {name:'level2Name'},
	                {name:'level1Id'},'isSelected','isAdd'
                 ]  
        });
		
		this.centerPanel =  new Ext.grid.EditorGridPanel({
			itemId:'search_form_grid',
			frame : false,
			columnLines :true,
			region : 'center', 
			//hidden:true,
			enableHdMenu : false,
			stripeRows: true,
			store:search_form_store,
			viewConfig:
			{
			scrollOffset:20
			},
			autoScroll : true,  	            
			clicksToEdit:1, 	             
			columns:[ 
				new Ext.grid.RowNumberer(),
				{
				 header:'操作',
				 xtype:'anchorcolumn',
				 width : 100,
				 dataIndex : 'act',
				 items:[
				   {
					text:"退货",
					scope:this,
					//permissionId:25,
					handler:this.addToReturned,
					getVisiblity : this.showAddLink
				   },{
					text:"取消",
					scope:this,
					//permissionId:25,
					handler:this.deleteReturnedItem,
					getVisiblity : this.showCancelLink
				   }
				 ]
				},
				{
				 header:'是否已选',
				 dataIndex : 'isSelected'
				},
				{header:'退货数量',dataIndex:'quantity',
					      editor:new Ext.form.NumberField({
								 allowBlank: false,
				 				 allowNegative: false
						  })	             			 
				},
				{header:'入库单号',dataIndex:'codeOfBuyer'},
			    {header:'剩余数量',dataIndex:'onHand'},
				{header:'零件编码',dataIndex:'code'},
				{header:'零件名称',dataIndex:'name'},
				{header:'车型',dataIndex:'carModel'},
				{header:'来源',dataIndex:'source',renderer:Ext.util.Format.comboRenderer(this.partSourceCombo)},
				{header:'单位',dataIndex:'measurementUnit'},
				{header:'进货数量',dataIndex:'orderQuantity'},			
				{header:'进价',dataIndex:'cost'},
				{header:'媒体价',dataIndex:'retailPrice'},
				{header:'最低价',dataIndex:'minPrice'},
				{header:'保险价',dataIndex:'insurancePrice'},
				{header:'品牌',dataIndex:'brand'},
				{header:'产地',dataIndex:'origin'},
				{header:'仓库',dataIndex:'storeName'},
				{header:'仓位',dataIndex:'shelf'}				
			]
		});
		
		config = Ext.apply(config||{},{items:[this.northPanel,this.centerPanel]});
		
		Uec3.AddReturnedItemWindow.superclass.constructor.call(this,config);
	},
	
	 //private
	initComponent:function(){
		Uec3.AddReturnedItemWindow.superclass.initComponent.call(this);
	},
	
	//private 
	initEvents : function(){
		Uec3.AddReturnedItemWindow.superclass.initEvents.call(this);
		this.partSourceCombo.getStore().load();
		this.centerPanel.on('validateedit',this.checkQuantity);
		this.centerPanel.on('mouseout',this.startLink,this);
		this.centerPanel.getStore().on('load',this.renderIsSelected,this);
	},
	
	renderIsSelected:function(store,records,options){
		var returnedItemRecords = this.params.returnedItemRecords;
		if(returnedItemRecords){			
			Ext.each(returnedItemRecords,function(record,index){
				var index = store.findExact('sourceInventoryId',record.get('sourceInventoryId'));
				if(index != -1){
					var loadedRecord = store.getAt(index);
					loadedRecord.set('quantity',record.get('quantity'));
					loadedRecord.set('isSelected','是');
				}
			});
		}
	},
	
	/**
	 * 判断欲退库数量和库存数
	 * @param {} e
	 */
	checkQuantity : function(e){
		if(e.field == 'quantity'){
			if(e.record.data.onHand < e.value){
				Ext.MessageBox.alert("提示","退货数量不能大于剩余数量!");
			    return false;
			}			
		}
		e.grid.getView().refresh();
	},
	
	startLink : function(e){		
		if(this.centerPanel.activeEditor){
			this.editCount++;
			if(this.editCount == 2){
				this.editCount = 0;
				this.centerPanel.stopEditing();
			}
		}
	},
	
	searchReceiveByCondition : function(){
		var partnerId = this.params.partnerComb.getValue();
		if(Ext.isEmpty(partnerId)){
			Ext.MessageBox.alert("提示","请先填写供货商信息");
		}else{
			var queryParam = this.northPanel.getForm().getValues();
			queryParam.partnerIdByBuyer = partnerId;
			var myMask = new Ext.LoadMask(this.el,{msg :"正在查询相关入库信息,请稍后..."});
			myMask.show();
			Ext.Ajax.request({
				url :Uec3.App.Constants.homeUrl+"/returned/toReturned!searchReturndItems.do",
				params :{queryParam:Ext.encode(queryParam)},
				method :"post",
				callback :function(options,success,response){
					myMask.hide();
				},
				success:function(response,options){
					var resp = Ext.decode(response.responseText);						       
					if(resp.length == 0){
						Ext.MessageBox.alert("提示",'未查询到来自该供货商的入库信息...');
					}else{
						this.centerPanel.getStore().loadData(resp);
					}			      
				},
				failure:function(response,options){
					Ext.MessageBox.alert("提示","网络连接异常，请稍后...");
				},
				scope:this
			});
		}
	},
	
	showAddLink : function(value,meta,record,rowIndex,colIndex,store){
		/*if(record.get('isSelected') == '否' || !record.get('isSelected')){
			return true;
		}
		return false;*/	
		return true;
	},
	
	showCancelLink : function(value,meta,record,rowIndex,colIndex,store){
		if(record.get('isSelected') == '是'){
			return true;
		}
		return false;
	},
	
	
	
	deleteReturnedItem : function(grid, rowIndex, colIndex, item, e){
		var fn = this.params.fn;
		if(fn && Ext.isFunction(fn))
		var record = grid.getStore().getAt(rowIndex);
		record.set('quantity','');
		record.set('isSelected','否');
		record.set('isAdd',false);
		fn(record);		
		grid.getView().refresh();
	},
	
	addToReturned : function(grid, rowIndex, colIndex, item, e){		
		var fn = this.params.fn;
		if(fn && Ext.isFunction(fn)){
			var record = grid.getStore().getAt(rowIndex);
			if(!record.get('quantity') || record.get('quantity') == 0){
				Ext.MessageBox.alert("提示",'请选择正确的退货数量!');
				return false;
			}else{
				record.set('isSelected','是');
				record.set('isAdd',true);
				fn(record);
			}
		}		
		grid.getView().refresh();
	}
});

Uec3.AddReturnedItemModule = Ext.extend(Ext.app.Module,{
	id: 'returnedItemAdd',	
	
	createWindow : function(params){			
		var desktop = this.app.getDesktop();
        var win = desktop.getWindow('addReturnedItemWindow');
		if(!win){
			win = desktop.createWindowNoTask({
				id: "addReturnedItemWindow",
				title: '采购退库明细增加',
				params : params,
				width: 1000,
				height: 500,
				minWidth:1000,
				minHeight:500,
				iconCls: 'acc-icon',
				shim: false,
				modal :true,
				animCollapse: false,
				constrainHeader: true,
				maximizable: true,
				minimizable : false,
				taskbuttonTooltip: "采购退库明细增加",
				layout: "border"         
			},Uec3.AddReturnedItemWindow);
		}else{
			win.params = params;
		}	
		win.show();
	} 
});